<template>
  <span>
    <template v-if="type === 'image-regular' || type === 'image-circle'">
      <div class="file-input" :class="type">
        <div class="image-container">
          <img v-if="type === 'image-regular'" :src="imageRegular" title="" />
          <img v-else :src="imageCircle" title="" />
        </div>
        <div class="button-container">
          <md-button
            v-if="hasImage"
            class="md-danger md-round"
            @click="removeImage"
            ><i class="fa fa-times" />Remove</md-button
          >
          <md-button class="md-success md-round md-fileinput">
            <template v-if="type === 'image-regular' && !hasImage"
              >Select image</template
            >
            <template v-else-if="type === 'image-circle' && !hasImage"
              >Add photo</template
            >
            <template v-else>Change</template>
            <input type="file" :name="type" @change="onFileChange" />
          </md-button>
        </div>
      </div>
    </template>

    <template v-else-if="type === 'input'">
      <template v-if="!withButton">
        <md-field class="form-file-upload form-file-simple">
          <md-input
            :id="inputName + 'Visible'"
            v-model="inputModel"
            :placeholder="placeholder"
            @click="triggerInputFileHidden(inputName + 'Hidden')"
          />
          <input
            :id="inputName + 'Hidden'"
            type="file"
            @change="newValue(inputName + 'Visible', inputName + 'Hidden')"
          />
        </md-field>
      </template>
      <template v-if="withButton">
        <div class="form-file-group">
          <md-field class="form-file-upload form-file-simple">
            <md-input
              ref="forBlur"
              class="myFileInput"
              :id="inputName + 'Visible'"
              v-model="inputModel"
              :multiple="multiple"
              :placeholder="placeholder"
              readonly
              @click="triggerInputFileHidden(inputName + 'Hidden')"
            />
            <input
              v-if="!multiple"
              :id="inputName + 'Hidden'"
              type="file"
              @change="newValue(inputName + 'Visible', inputName + 'Hidden')"
            />
            <input
              v-else
              :id="inputName + 'Hidden'"
              type="file"
              :multiple="multiple"
              @change="
                newValueMultiple(inputName + 'Visible', inputName + 'Hidden')
              "
            />
          </md-field>
          <md-button
            class="myBtn md-simple md-just-icon"
            @click="triggerInputFileHidden(inputName + 'Hidden')"
            ><md-icon>{{ btnIcon }}</md-icon></md-button
          >
        </div>
      </template>
    </template>
  </span>
</template>

<script>
export default {
  name: "FileUpload",
  props: {
    type: String,
    inputName: String,
    inputValue: String,
    placeholder: String,
    multiple: Boolean,
    btnIcon: String,
    withButton: Boolean,
    defaultCircle: String,
  },
  data() {
    return {
      inputModel: null,
      inputModel2: null,
      imageRegular: require("@/assets/images/mobile_black/home/avatar_default.png"),
      imageCircle:
        this.defaultCircle ||
        require("@/assets/images/mobile_black/home/avatar_default.png"),
      hasImage: false,
    };
  },
  methods: {
    onFileChange(e) {
      e.preventDefault();
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      let file = files[0];
      let reader = new FileReader();
      let vm = this;
      reader.onload = () => {
        if (this.type === "image-circle") {
          vm.imageCircle = reader.result;
        } else {
          vm.imageRegular = reader.result;
        }
      };
      reader.readAsDataURL(file);
      vm.hasImage = true;
      this.$emit("uploadImage", files);
    },
    removeImage: function () {
      if (this.type === "image-circle") {
        // this.imageCircle = require("@/assets/img/placeholder.jpg");
      } else {
        // this.imageRegular = require("@/assets/img/image_placeholder.jpg");
      }
      this.hasImage = false;
    },
    triggerInputFileHidden(hiddenID) {
      let element = document.getElementById(hiddenID);
      element.click();
    },
    newValue(visibleID, hiddenID) {
      let element = document.getElementById(hiddenID);
      let visibleElem = document.getElementById(visibleID);
      let elemValue = element.value;
      let filename = elemValue.replace(/C:\\fakepath\\/i, "");

      // 获取上传文件的真实路径（由于浏览器的安全机制，input file的路径时被fakepath代替，隐藏了真实物理路径。）
      // -解决方式：使用window.URL.createObjectURL()
      // -注释：URL.createObjectURL()方法会根据传入的参数创建一个指向该参数对象的URL，这个URL的生命仅存在于它被创建的这个文档里，新的对象URL指向执行的File对象或Blob对象。每次调用createObjectURL的时候，一个新的URL对象就被创建了。即使你已经为同一个文件创建过一个URL.，如果你不再需要这个对象，要释放它，需要使用URL.revokeObjectURL()方法.。当页面被关闭，浏览器会自动释放它，但是为了最佳性能和内存使用，当确保不再用得到它的时候,就应该释放它。
      var url = null;
      var fileObj = element.files[0];
      if (window.createObjcectURL != undefined) {
        url = window.createOjcectURL(fileObj);
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(fileObj);
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(fileObj);
      }
      this.$emit("uploadFiles", element.files, url);
      // URL.revokeObjectURL();

      visibleElem.value = filename;
    },
    newValueMultiple(visibleID, hiddenID) {
      let element = document.getElementById(hiddenID);
      let visibleElem = document.getElementById(visibleID);
      let names = "";
      for (var i = 0; i < element.files.length; ++i) {
        if (i < element.files.length - 1) {
          names += element.files.item(i).name + ", ";
        } else {
          names += element.files.item(i).name;
        }
      }

      visibleElem.value = names;
    },
  },
};
</script>

<style lang="less">
.myBtn {
  width: 48px;
  height: 40px;
  background: #ffffff;
  border: 1px solid #e5e5e5 !important;
  transform: translate(-3px, -11px);
}
.myFileInput {
  width: 109px;
  height: 40px;
  background: #ffffff;
  transform: translateY(-12px);
}
</style>
